package com.gcq.javawork.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gcq.javawork.model.domain.User;
import com.gcq.javawork.service.UserService;
import com.gcq.javawork.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.gcq.javawork.constatnts.UserConstants.USER_LOGIN_STATUS;

/**
* @author guochuqu
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2024-09-07 11:14:40
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

     private static final  String SALT = "gcq"; //盐值



    @Resource
    private UserMapper userMapper;

    @Override
    public long userRegistered(String userAccount, String userPassword, String checkPassword) {
        //1.检验账号和密码
        //非空判断
        //todo 自定义异常
        if(!(StringUtils.isNotBlank(userAccount) && StringUtils.isNotBlank(userPassword) && StringUtils.isNotBlank(checkPassword))){
            return -1;
        }
        //长度判读
        if (userAccount.length() < 4 || userPassword.length() < 6){
            return -1;
        }
          Pattern pattern= Pattern.compile("^[a-zA-Z0-9_]+$");
      //testStr被检测的文本
          Matcher matcher = pattern.matcher(userAccount);
        //匹配上的时候返回true,匹配不通过返回false
          matcher.matches();

        //账号不能有特殊符号
        if (!matcher.matches()) {
            return -1;
        }
        //密码校验
        if(!userPassword.equals(checkPassword)){
            return -1;
        }
        //账号重复判断
        if (userMapper.selectCount(new QueryWrapper<User>().eq("userAccounts", userAccount)) > 0) { //数据库中存在该账号
            return -1;
        }
        //2.加密密码

        String encryptPassword = DigestUtils.md5DigestAsHex((userPassword + SALT).getBytes());//加密
        User user = new User();
        user.setUserAccounts(userAccount);
        user.setUserPassword(encryptPassword);
      //  System.out.println(user);
        boolean result = this.save(user);
        if (!result) {
            return -1;
        }

        return 0;
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1. 检验用户名和密码是否合法
        if(!(StringUtils.isNotBlank(userAccount) && StringUtils.isNotBlank(userPassword))){
            return null;
        }
        //长度判读
        if (userAccount.length() < 4 || userPassword.length() < 6){
            return null;
        }
        Pattern pattern= Pattern.compile("^[a-zA-Z0-9_]+$");
        //testStr被检测的文本
        Matcher matcher = pattern.matcher(userAccount);
        //匹配上的时候返回true,匹配不通过返回false
        matcher.matches();

        //账号不能有特殊符号
        if (!matcher.matches()) {
            return null;
        }
        //2.检验密码
        String encryptPassword = DigestUtils.md5DigestAsHex((userPassword + SALT).getBytes());//加密
        User user = new User();
        user.setUserAccounts(userAccount);
        user.setUserPassword(encryptPassword);
        User handled = userMapper.selectOne(new QueryWrapper<>(user));
        if (handled == null) {
            log.info("user login failed, userAccount and userPassword not match ");
            return null;
        }
        //用户脱敏
        User safeUser = userDesensitization(handled);


        //记录用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATUS,handled);

        return safeUser;
    }

    @Override
    public List<User> searchUserByName(String userName) {
       List<User> users = userMapper.selectList(new QueryWrapper<User>().like("userName", userName));
       List<User> userList = users.stream().map
               (this::userDesensitization).collect(Collectors.toList());
        return userList;
    }


    public User userDesensitization(User handled){
        if (handled == null){
            return null;
        }
        User safeUser = new User();
        safeUser.setUsername(handled.getUsername());
        safeUser.setUserAccounts(handled.getUserAccounts());
        safeUser.setAvatarUrl(handled.getAvatarUrl());
        safeUser.setGender(handled.getGender());
        safeUser.setUserState(handled.getUserState());
        safeUser.setCreateTime(handled.getCreateTime());
        safeUser.setUpdateTime(handled.getUpdateTime());
        safeUser.setUserRole(handled.getUserRole());
        return safeUser;
    }
    
}




